package com.gitee.zeric.tenantdb.demo.controller;


import com.gitee.zeric.tenantdb.config.DynamicDataSource;
import com.gitee.zeric.tenantdb.demo.entity.CustomResult;
import com.gitee.zeric.tenantdb.demo.entity.TenantInfo;
import com.gitee.zeric.tenantdb.demo.service.ITenantInfoService;
import com.gitee.zeric.tenantdb.demo.utils.ResultEnum;
import com.gitee.zeric.tenantdb.utils.SpringContextUtil;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  租户接口
 *
 * @author zj
 * @date 2022/11/25
 */
@Slf4j
@RestController
@RequestMapping("/tenantInfo")
public class TenantInfoController {

    @Autowired
    private ITenantInfoService tenantInfoService;


    /**
     * 获取所有租户信息
     *
     * @return {@link CustomResult}<{@link TenantInfo}>
     */
    @GetMapping("/info")
    public CustomResult<List<TenantInfo>> getInfo() {
        List<TenantInfo> list = tenantInfoService.list();
        return CustomResult.Ok(list);
    }

    /**
     * 动态添加租户
     *
     * @return {@link CustomResult}<{@link ?}>
     */
    @GetMapping("/save")
    public CustomResult<?> saveInfo() {
        TenantInfo tenantInfo = new TenantInfo();
        tenantInfo.setId(2L);
        tenantInfo.setDatasourceUrl("jdbc:mysql://172.16.3.218:3306/{db}?serverTimezone=Asia/Shanghai&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8");
        tenantInfo.setDatasourceUsername("root");
        tenantInfo.setDatasourcePassword("Root123...");
        tenantInfo.setDatasourceDriver("com.mysql.cj.jdbc.Driver");
        tenantInfo.setDatasourceDriver("com.alibaba.druid.pool.DruidDataSource");
        boolean b = tenantInfoService.save(tenantInfo);
        if (b) {
            log.info("======初始化动态数据源=====");
            DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtil.getBean("dynamicDataSource");
            HikariDataSource master = (HikariDataSource) SpringContextUtil.getBean("master");
            Map<Object, Object> dataSourceMap = new HashMap<>();
            dataSourceMap.put("master", master);

            List<TenantInfo> tenantList = tenantInfoService.list();
            for (TenantInfo tenantInfos : tenantList) {
                log.info(tenantInfos.getId() + "     " + tenantInfos.getDatasourceDriver());
                HikariDataSource dataSource = new HikariDataSource();
                dataSource.setDriverClassName(tenantInfos.getDatasourceDriver());
                dataSource.setJdbcUrl(tenantInfos.getDatasourceUrl());
                dataSource.setUsername(tenantInfos.getDatasourceUsername());
                dataSource.setPassword(tenantInfos.getDatasourcePassword());
                dataSource.setDataSourceProperties(master.getDataSourceProperties());
                dataSourceMap.put(tenantInfos.getId(), dataSource);
            }
            // 设置数据源
            dynamicDataSource.setDataSources(dataSourceMap);
            /**
             * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
             */
            dynamicDataSource.afterPropertiesSet();
        }
        return CustomResult.Build(b, b ? ResultEnum.Success.getIndex() : ResultEnum.Fail.getIndex());
    }
}
